<template>
  <div class="work-mall-share">
    <div class="work-mall-header">
      <bottom-open-app-adv
        v-if="!$UA.isJM"
        v-app-jump="{ to: `mtjimu://homepage?uid=${this.uuid}` }"
      ></bottom-open-app-adv>
      <van-nav-bar
        title="作品墙海报"
        left-arrow
        @click-left="back"
        class="my-nav-bar"
        v-if="$UA.isJM"
      ></van-nav-bar>
    </div>
    <div class="work-mall-main" :class="{ notJM: $UA.isJM ? false : true }">
      <!-- 页面最终生成的图片 -->
      <img :src="imgUrl" alt="" class="show-img" v-if="imgUrl" />
      <div v-else class="load-box">
        <van-loading vertical>正在加载...</van-loading>
      </div>
      <div class="hidden" ref="imageWrapper">
        <div class="work-box">
          <div class="work-header">
            <!-- <img
              :src="userBaseData.avatar + '?' + new Date().getTime()"
              crossorigin="anonymous"
              alt=""
            /> -->
            <img v-if="avatarImg" :src="avatarImg" crossorigin="anonymous" alt="" />
            <span class="nickname">
              {{
                userBaseData.nickname && userBaseData.nickname.slice(9)
                  ? userBaseData.nickname.replace(userBaseData.nickname.slice(9), '...')
                  : userBaseData.nickname
              }}
            </span>
            <span class="total">
              共
              <span class="total-big">{{ userWorkWallData.total }}</span>
              个影视作品
            </span>
          </div>
          <div class="work-main" v-if="userWorkWallData.rows">
            <div
              v-for="(item, index) in userWorkWallData.rows.slice(0, 6)"
              class="film-item"
              :key="index"
            >
              <div class="film-cover">
                <!-- <img
                  :src="item.cover + '?' + new Date().getTime()"
                  @error="
                    (e) => {
                      errorImg(e, item);
                    }
                  "
                  crossorigin="anonymous"
                  alt=""
                /> -->
                <img v-if="item.coverImg" :src="item.coverImg" crossorigin="anonymous" alt="" />
                <div class="film-info">
                  <span>{{ item.onlineYear }}</span>
                  <!-- <span v-if="item.boxOffice">票房: {{ item.boxOffice }}</span> -->
                  <span v-if="item.boxOffice" class="film-boxOffice">
                    {{
                      item.boxOffice.slice(5)
                        ? '票房: ' + item.boxOffice.replace(item.boxOffice.slice(5), '...')
                        : '票房: ' + item.boxOffice
                    }}
                  </span>
                </div>
              </div>
              <div class="file-name">
                {{
                  item.title.slice(10)
                    ? item.title.replace(item.title.slice(10), '...')
                    : item.title
                }}
              </div>
              <div class="film-cateory">
                <img src="../../assets/images/job.png" v-if="item.job" alt="" />
                <span>
                  {{ item.job.slice(8) ? item.job.replace(item.job.slice(8), '...') : item.job }}
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="more-open-jm" v-if="userWorkWallData.rows && userWorkWallData.rows.length > 6">
          <img src="../../assets/images/more-open-jm.png" alt="" />
        </div>
        <div class="share-qr-code">
          <div class="qr-code">
            <canvas id="my-qr-code"></canvas>
          </div>
          <div class="jm-info">
            <p>长按识别二维码</p>
            <p>查看作品、沟通合作</p>
          </div>
          <div class="jm-img">
            <img src="../../assets/images/logo.png" alt="" />
          </div>
        </div>
      </div>
    </div>
    <div class="work-mall-footer" v-if="shareInfo.image && $UA.isJM">
      <share-bottom-btn
        :shareInfo.sync="shareInfo"
        :shareSize="shareSize"
        :shareType="shareType"
      ></share-bottom-btn>
    </div>
  </div>
</template>
<script>
  import { NavBar, Loading, Toast } from 'vant';
  import ShareBottomBtn from '../../components/ShareBottomBtn.vue';
  import qs from 'qs';
  import BottomOpenAppAdv from '../../components/BottomOpenAppAdv.vue';
  import QRCode from 'qrcode';
  import html2canvas from 'html2canvas';

  import imgAxios from 'axios';

  export default {
    data() {
      return {
        shareInfo: {
          //分享的图片
          image: 'https://www.baidu.com',
        },
        imgUrl: '', //生成的图片
        shareUrl: '', //二维码的链接
        userBaseData: {}, //用户基本数据
        userWorkWallData: {}, //用户作品墙数据
        // 二维码配置
        opts: {
          errorCorrectionLevel: 'L', //容错级别
          type: 'image/png', //生成的二维码类型
          quality: 0.3, //二维码质量
          margin: 0, //二维码留白边距
          width: 50, //宽
          height: 50, //高
          text: 'https://www.github.com', //二维码内容
          color: {
            dark: '#000', //前景色
            light: '#fff', //背景色
          },
        },
        avatarImg: '', //头像
        shareSize: '450', //分享的大小
        shareType: 'shareWall', //分享的类型
      };
    },
    components: {
      'van-nav-bar': NavBar,
      'van-loading': Loading,
      ShareBottomBtn,
      BottomOpenAppAdv,
    },
    computed: {
      uuid() {
        const { uuid } = qs.parse(window.location.search.replace(/^\?/, ''));
        return uuid;
      },
    },
    mounted() {
      // 设置全屏
      this.$appService.setNav({
        title: '作品墙海报',
        fullscreen: true,
        statusBarStyle: 0,
      });

      // 这里是禁止微信分享
      this.hideWXShare();

      if (!this.uuid) {
        Toast('缺少uuid');
        return;
      } else {
        // 得到数据
        this.getUserBaseData();
        // 设置二维码的链接
        this.shareUrl = `https://${
          process.env.NODE_ENV === 'development' ? 'dev-' : ''
        }jimu-h5.movtile.com/user.html?id=${this.uuid}`;
        // 生成二维码
        this.getQRCode();
      }

      // setTimeout(() => {
      //   this.getShareImg();
      // }, 9000);

      // this.$nextTick(() => {
      //   this.getShareImg();
      // });
    },
    methods: {
      // 图片加载失败
      // errorImg(e, item) {
      //   e.target.src = item.cover;
      //   this.$forceUpdate();
      // },

      // 图片转化
      getBase64Image(imgurl, key) {
        return new Promise((resolve, reject) => {
          var img = new Image();
          img.setAttribute('crossOrigin', 'anonymous');
          var canvas = document.createElement('canvas');
          let _imgurl = imgurl;
          switch (key) {
            case 'cover':
              img.src = _imgurl + '?' + new Date().getTime();
              img.setAttribute('base64Key', key);
              canvas.width = 142 * 2;
              canvas.height = 210 * 2;
              break;
            case 'avatar':
            default:
              //这个设置不能丢，否者会成为canvas默认的300*150的大小
              img.src = _imgurl + '?' + new Date().getTime();
              canvas.width = 32;
              canvas.height = 32;
          }
          var ctx = canvas.getContext('2d');
          img.onload = () => {
            // 这是做个cover效果
            if (img.getAttribute('base64Key')) {
              let imgRect = this.coverImg(canvas.width, canvas.height, img.width, img.height);
              ctx.drawImage(
                img,
                imgRect.sx,
                imgRect.sy,
                imgRect.sWidth,
                imgRect.sHeight,
                0,
                0,
                canvas.width,
                canvas.height,
              );
            } else {
              ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
            }
            resolve(canvas.toDataURL());
          };
          img.onerror = (err) => {
            // 图片 url 不存在的时候就让页面继续加载吧。。
            resolve();
          };
        });
      },

      // cover效果
      coverImg(box_w, box_h, source_w, source_h) {
        var sx = 0,
          sy = 0,
          sWidth = source_w,
          sHeight = source_h;
        if (source_w > source_h || (source_w == source_h && box_w < box_h)) {
          sWidth = (box_w * sHeight) / box_h;
          sx = (source_w - sWidth) / 2;
        } else if (source_w < source_h || (source_w == source_h && box_w > box_h)) {
          sHeight = (box_h * sWidth) / box_w;
          sy = (source_h - sHeight) / 2;
        }
        return {
          sx,
          sy,
          sWidth,
          sHeight,
        };
      },

      // 生成图片
      getShareImg() {
        html2canvas(this.$refs.imageWrapper, {
          allowTaint: true,
          useCORS: true,
          dpi: 96 * window.devicePixelRatio, // 处理模糊
          scale: this.$UA.isAndroid ? 1 : window.devicePixelRatio,
        }).then((canvas) => {
          let dataURL = canvas.toDataURL('image/png');
          // imgAxios
          //   .post('https://api.tinify.com', dataURL, {
          //     headers: {
          //       Authorization: 'Basic JPh5gKW6xrfqgBkJk4fVTB1mMswPrP3W',
          //     },
          //   })
          //   .then((res) => console.log(res))
          //   .catch((err) => console.log(err));
          this.imgUrl = dataURL;
          this.shareInfo.image = this.imgUrl;
        });
      },

      // 生成二维码
      getQRCode() {
        let msg = document.getElementById('my-qr-code');
        // 将获取到的数据（val）画到msg（canvas）上
        QRCode.toCanvas(msg, this.shareUrl, { ...this.opts }, function(error) {
          console.log(error);
        });
      },

      // 获得作品墙
      getUserWorkWallData() {
        this.$service
          .UserFilmWall({ uid: this.uuid, page: 1, size: 7 })
          .then((res) => {
            this.userWorkWallData = res;

            if (this.userWorkWallData.rows && !this.userWorkWallData.rows.length) {
              Toast('该用户没有作品！');
            }

            let pArr = [];
            this.$nextTick(() => {
              pArr.push(
                this.getBase64Image(this.userBaseData.avatar, 'avatar').then((res) => {
                  this.avatarImg = res;
                }),
              );
              this.userWorkWallData.rows.map((item) => {
                pArr.push(
                  this.getBase64Image(item.cover, 'cover').then((r) => {
                    this.$set(item, 'coverImg', r);
                  }),
                );
              });
              Promise.all(pArr).then(() => {
                this.getShareImg();
              });
            });

            // this.$nextTick(() => {
            //   this.getShareImg();
            // });
          })
          .catch((err) => {
            Toast(err);
          });
      },

      // 获得基本信息
      getUserBaseData() {
        this.$service
          .UserInfoDetail({ uuid: this.uuid })
          .then((res) => {
            this.userBaseData = res;

            this.getUserWorkWallData();
          })
          .catch((err) => {
            Toast(err);
          });
      },

      // 返回
      back() {
        this.$appService.exit();
      },

      // 这里是禁止微信分享
      hideWXShare() {
        function onBridgeReady() {
          WeixinJSBridge.call('hideOptionMenu'); //隐藏微信下的分享菜单
        }
        if (typeof WeixinJSBridge == 'undefined') {
          if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
          } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
          }
        } else {
          onBridgeReady();
        }
      },
    },
  };
</script>
<style lang="less" scoped>
  .page-bottom-open-app {
    background-color: white !important;
    color: #111 !important;
    top: 0 !important;
    z-index: 30 !important;
  }

  .work-mall-share {
    color: #ddd;
    background-color: #151826;
    height: 100vh;
    width: 100%;
    position: relative;
    overflow: hidden;

    .my-nav-bar {
      background-color: transparent;
      height: 8.4rem;
      padding-top: 3.5rem;
    }
    // vant 样式修改
    /deep/ .van-nav-bar {
      .van-nav-bar__title {
        color: #fff;
        font-weight: 600;
        font-size: 18px;
      }
      .van-nav-bar__arrow {
        font-size: 18px;
      }
      .van-icon {
        color: #fff;
      }
    }
    /deep/ .van-hairline--bottom::after {
      border-bottom-width: 0px;
    }

    .work-mall-main {
      position: relative;
      overflow-y: auto;
      overflow-x: hidden;
      margin: 2rem;
      border-radius: 0.5rem;
      height: calc(100vh - 8.4rem - 2rem - 2rem - 17.2rem);
      background-color: #1d2132;
      &::-webkit-scrollbar {
        display: none;
      }
      .load-box {
        position: absolute;
        top: 39%;
        left: 0;
        right: 0;
      }

      .show-img {
        width: 100%;
      }

      .hidden {
        // 这因为有滚动最好使用fixed，不然有白屏
        position: fixed;
        top: 0rem;
        left: 30000rem;
        background-color: #1d2132;
        font-size: 1.4rem;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        line-height: 20px;
        overflow: hidden;
        .work-box {
          padding: 2.8rem 1.8rem 0rem;
        }
        .work-header {
          display: flex;
          align-items: center;
          img {
            flex-shrink: 0;
            width: 3.2rem;
            height: 3.2rem;
            border-radius: 50%;
            border: 2px solid rgba(255, 255, 255, 0.15);
          }
          .nickname {
            flex: 1;
            margin-left: 0.8rem;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .total {
            font-size: 1.2rem;
            font-weight: 300;
            line-height: 17px;
            .total-big {
              font-size: 18px;
              font-family: DIN-Bold, DIN;
              font-weight: bold;
            }
          }
        }
        .work-main {
          margin-top: 2.2rem;
          display: grid;
          grid-template-columns: repeat(2, calc(50% - 8px));
          grid-gap: 19px 15px;
          justify-items: center;
          .film-item {
            .film-cover {
              position: relative;
              width: 142px;
              height: 210px;
              img {
                display: block;
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
                width: 142px;
                height: 210px;
                object-fit: cover;
                border-radius: 5px;
              }
              .film-info {
                position: absolute;
                bottom: -1px;
                left: -1px;
                width: 143px;
                height: 211px;
                padding: 0.7rem 1rem;
                background: linear-gradient(
                  180deg,
                  rgba(0, 0, 0, 0) 0%,
                  rgba(0, 0, 0, 0) 60%,
                  #000000 100%
                );
                border-radius: 0px 0px 5px 5px;
                display: flex;
                justify-content: space-between;
                align-items: flex-end;
                span {
                  overflow: hidden;
                  white-space: nowrap;
                  max-width: 143px;
                }
                .film-boxOffice {
                  flex: 1;
                  margin-left: 1rem;
                }
              }
            }
            .file-name {
              margin-top: 1rem;
              font-size: 14px;
              font-family: PingFangSC-Medium, PingFang SC;
              font-weight: 500;
              color: #ffffff;
              overflow: hidden;
              white-space: nowrap;
              max-width: 142px;
              text-overflow: ellipsis;
            }
            .film-cateory {
              height: 2rem;
              margin-top: 0.6rem;
              font-size: 14px;
              font-family: PingFangSC-Light, PingFang SC;
              font-weight: 300;
              color: #eed5a7;
              display: flex;
              align-items: center;
              img {
                width: 8px;
                height: 15px;
                margin-right: 0.5rem;
              }
            }
          }
        }
        .more-open-jm {
          overflow: hidden;
          padding: 2rem 4.6rem 2rem;
          height: 2rem;
          img {
            height: 2rem;
          }
        }
        .share-qr-code {
          overflow: hidden;
          margin-top: 2rem;
          height: 8rem;
          background-color: #fff;
          padding: 1.5rem;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .qr-code {
            width: 5rem;
            height: 5rem;
            flex-shrink: 0;
          }
          .jm-info {
            flex: 1;
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #111111;
            line-height: 20px;
            margin-left: 1rem;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            &:last-child {
              font-weight: 300;
            }
          }
          .jm-img {
            margin-right: 2rem;
            img {
              width: 70px;
              height: 23px;
            }
          }
        }
      }
    }

    // 不在app里的时候的控制高度
    .notJM {
      margin-top: 8.5rem;
      height: calc(100vh - 8.5rem - 2rem);
    }
  }
</style>
